package com.draven.order.controller;

import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class LogionController {

    private final TokenStore tokenStore = new InMemoryTokenStore();

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password) {
        // 这里可以添加实际的认证逻辑，例如调用UserDetailsService进行认证
        // 为了示例，我们假设认证成功
        if ("user".equals(username) && "password".equals(password)) {
            // 生成OAuth2访问令牌
            OAuth2AccessToken accessToken = generateAccessToken(username);
            tokenStore.storeAccessToken(accessToken, createOAuth2Authentication(username));
            return "Login successful. Access Token: " + accessToken.getValue();
        } else {
            return "Login failed";
        }
    }

    private OAuth2AccessToken generateAccessToken(String username) {
        DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
        accessToken.setTokenType("bearer");
        accessToken.setExpiration(new java.util.Date(System.currentTimeMillis() + 3600000)); // 1 hour
        return accessToken;
    }

    private OAuth2Authentication createOAuth2Authentication(String username) {
        // 这里可以创建一个简单的OAuth2Authentication对象
        // 为了示例，我们返回一个简单的对象
        return new OAuth2Authentication(null, null);
    }
}